package com.hig.onlineexam.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import com.hig.exam.domain.ExamTaskManager;
import com.hig.exam.service.IExamTaskManagerService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.hig.onlineexam.domain.ExamTaskAnswer;
import com.hig.onlineexam.service.IExamTaskAnswerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考试实时数据Controller
 * 
 * @author qnsdt
 * @date 2023-02-24
 */
@Api("考试实时数据")
@RestController
@RequestMapping("/onlineexam/taskanswer")
public class ExamTaskAnswerController extends BaseController
{
    @Autowired
    private IExamTaskAnswerService examTaskAnswerService;

    /**
     * 查询考试实时数据列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ExamTaskAnswer examTaskAnswer)
    {
        startPage();
        List<ExamTaskAnswer> list = examTaskAnswerService.selectExamTaskAnswerList(examTaskAnswer);
        return getDataTable(list);
    }

    /**
     * 导出考试实时数据列表
     */
    @GetMapping("/export")
    public AjaxResult export(ExamTaskAnswer examTaskAnswer)
    {
        List<ExamTaskAnswer> list = examTaskAnswerService.selectExamTaskAnswerList(examTaskAnswer);
        ExcelUtil<ExamTaskAnswer> util = new ExcelUtil<ExamTaskAnswer>(ExamTaskAnswer.class);
        return util.exportExcel(list, "考试实时数据数据");
    }

    /**
     * 获取考试实时数据详细信息
     */
    @GetMapping(value = "/{examCode}")
    public AjaxResult getInfo(@PathVariable("examCode") String examCode)
    {
        return AjaxResult.success(examTaskAnswerService.selectExamTaskAnswerById(examCode));
    }

    /**
     * 新增考试实时数据
     */
    @ApiOperation("新增考试实时数据（每个题第一次提交答案）")
    @PostMapping
    public AjaxResult add(@RequestBody ExamTaskAnswer examTaskAnswer)
    {
        String examCode = examTaskAnswer.getExamCode();
        ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);
        if (ObjectUtil.isNull(examTaskManager)){
            throw new RuntimeException("查询不到考试信息");
        }
        String buildType = examTaskManager.getBuildType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        if ("3".equals(buildType)){
            //随机打乱顺序
            String questionsCode = examTaskAnswer.getQuestionsCode();
            Map<String, Object> cacheMap = redisCache.getCacheMap(examCode + questionsCode + userId);
            if (ObjectUtil.isNotNull(cacheMap)){
                String questionsAnswer = examTaskAnswer.getQuestionsAnswer();
                Long questionsType = examTaskAnswer.getQuestionsType();
                if (questionsType!=3){
                    String o = (String) cacheMap.get(questionsAnswer);
                    examTaskAnswer.setQuestionsAnswer(o);
                }else {
                    if (StringUtils.isNotBlank(questionsAnswer)){
                        String[] split = questionsAnswer.split(",");
                        ArrayList<String> list = new ArrayList<>();
                        for (String s : split) {
                            String o = (String) cacheMap.get(s);
                            list.add(o);
                        }
// 对选项进行排序
                        list.sort(String::compareTo); // 默认按照字母顺序排序

// 拼接成 A,B,C,D 格式
                        String result = String.join("", list);
                        examTaskAnswer.setQuestionsAnswer(result);
                    }

                }

            }
        }
        return toAjax(examTaskAnswerService.insertExamTaskAnswer(examTaskAnswer));
//        return toAjax(examTaskAnswerService.updateExamTaskAnswer(examTaskAnswer));
    }
    @Autowired
    private IExamTaskManagerService examTaskManagerService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;
    /**
     * 修改考试实时数据
     */
    @ApiOperation("修改考试实时数据（每个题提交答案）")
    @PutMapping
    public AjaxResult edit(@RequestBody ExamTaskAnswer examTaskAnswer)
    {
        String examCode = examTaskAnswer.getExamCode();
        ExamTaskManager examTaskManager = examTaskManagerService.selectExamTaskManagerById(examCode);
        if (ObjectUtil.isNull(examTaskManager)){
            throw new RuntimeException("查询不到考试信息");
        }
        String buildType = examTaskManager.getBuildType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        if ("3".equals(buildType)){
            //随机打乱顺序
            String questionsCode = examTaskAnswer.getQuestionsCode();
            Map<String, Object> cacheMap = redisCache.getCacheMap(examCode + questionsCode + userId);
            if (ObjectUtil.isNotNull(cacheMap)){
                String questionsAnswer = examTaskAnswer.getQuestionsAnswer();
                Long questionsType = examTaskAnswer.getQuestionsType();
                if (questionsType!=3){
                    String o = (String) cacheMap.get(questionsAnswer);
                    examTaskAnswer.setQuestionsAnswer(o);
                }else {
                    if (StringUtils.isNotBlank(questionsAnswer)){
                        String[] split = questionsAnswer.split(",");
                        ArrayList<String> list = new ArrayList<>();
                        for (String s : split) {
                            String o = (String) cacheMap.get(s);
                            list.add(o);
                        }
// 对选项进行排序
                        list.sort(String::compareTo); // 默认按照字母顺序排序

// 拼接成 A,B,C,D 格式
                        String result = String.join("", list);
                        examTaskAnswer.setQuestionsAnswer(result);
                    }

                }

            }
        }
        return toAjax(examTaskAnswerService.insertExamTaskAnswer(examTaskAnswer));
//        return toAjax(examTaskAnswerService.updateExamTaskAnswer(examTaskAnswer));
    }

    /**
     * 删除考试实时数据
     */
	@GetMapping("/remove/{examCodes}")
    public AjaxResult remove(@PathVariable String[] examCodes)
    {
        return toAjax(examTaskAnswerService.deleteExamTaskAnswerByIds(examCodes));
    }
    
    /**
     * 删除考试实时数据
     */
	@PostMapping("/delete")
    public AjaxResult delete(ExamTaskAnswer examTaskAnswer)
    {
        return toAjax(examTaskAnswerService.deleteExamTaskAnswer(examTaskAnswer));
    }
}
